<template>
  <div class="article-type-management">
    <div class="page-header">
      <h2>文章分类管理</h2>
      <div class="page-info">
        <el-tag size="small" type="info">数据统计</el-tag>
        <span class="stat-item"><i class="el-icon-collection-tag"></i> 分类总数：{{ filteredCategories.length }}</span>
      </div>
    </div>
    
    <!-- 操作工具栏 -->
    <el-card class="box-card" shadow="hover">
      <div class="toolbar">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增分类</el-button>
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item>
            <el-input v-model="searchForm.name" placeholder="分类名称" size="small" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-select v-model="searchForm.status" clearable placeholder="状态" size="small">
              <el-option :value="1" label="启用"></el-option>
              <el-option :value="0" label="禁用"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" icon="el-icon-search" @click="onSearch">查询</el-button>
            <el-button size="small" icon="el-icon-refresh" @click="resetSearchForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    
      <!-- 分类统计卡片 -->
      <div class="stat-cards">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-collection-tag"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ filteredCategories.length }}</div>
            <div class="stat-label">分类总数</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon" style="background-color: #67c23a;">
            <i class="el-icon-check"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ getStatusCount(1) }}</div>
            <div class="stat-label">启用分类</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon" style="background-color: #909399;">
            <i class="el-icon-close"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ getStatusCount(0) }}</div>
            <div class="stat-label">禁用分类</div>
          </div>
        </div>
      </div>

      <!-- 表格 -->
      <el-table 
        :data="filteredCategories" 
        border 
        style="width: 100%; margin-top: 15px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); border-radius: 4px;" 
        v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :row-class-name="tableRowClassName"
        :stripe="true"
        :highlight-current-row="true">
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="name" label="分类名称" width="180">
          <template slot-scope="scope">
            <el-tag size="medium" effect="plain" class="category-name-tag">{{ scope.row.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="300" show-overflow-tooltip></el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="100" align="center"></el-table-column>
        <el-table-column label="状态" width="120" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'" size="small">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="240" align="center">
          <template slot-scope="scope">
            <el-button @click="handleEdit(scope.row)" type="text" size="small">
              <i class="el-icon-edit"></i> 编辑
            </el-button>
            <el-button @click="handleStatus(scope.row)" type="text" size="small">
              <i :class="scope.row.status === 1 ? 'el-icon-close' : 'el-icon-check'"></i> 
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button @click="handleDelete(scope.row)" type="text" size="small" style="color: #F56C6C">
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 无数据提示 -->
      <div v-if="!loading && filteredCategories.length === 0" class="empty-container">
        <el-empty description="暂无分类数据">
          <el-button type="primary" size="small" @click="handleAdd">添加分类</el-button>
        </el-empty>
      </div>
      
      <!-- 使用提示 -->
      <div class="tips-container" v-if="filteredCategories.length > 0">
        <div class="tip-icon"><i class="el-icon-info"></i></div>
        <div class="tip-content">
          <div class="tip-title">使用提示</div>
          <div class="tip-text">
            <p>1. 分类一旦创建并使用，修改名称可能影响现有文章</p>
            <p>2. 禁用分类后，该分类下的文章在前台将不可见</p>
            <p>3. 删除分类前，请确保该分类下没有关联的文章</p>
          </div>
        </div>
      </div>
    </el-card>
    
   
    
    <!-- 编辑/新增对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @close="resetForm('categoryForm')" top="10vh">
      <el-form :model="categoryForm" :rules="rules" ref="categoryForm" label-width="100px" status-icon>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" maxlength="50" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="categoryForm.description" type="textarea" rows="3" placeholder="请输入描述" maxlength="255" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="categoryForm.sortOrder" :min="0" :max="999" controls-position="right"></el-input-number>
          <div class="form-tip">数字越小越靠前</div>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="categoryForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm('categoryForm')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'ArticleTypeManagement',
  data() {
    return {
      loading: false,
      categoriesList: [],
      searchForm: {
        name: '',
        status: null
      },
      dialogVisible: false,
      dialogTitle: '新增分类',
      isEdit: false,
      categoryForm: {
        id: null,
        name: '',
        description: '',
        sortOrder: 0,
        status: 1
      },
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        description: [
          { max: 255, message: '描述不能超过255个字符', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    filteredCategories() {
      return this.categoriesList.filter(item => {
        // 名称筛选
        const nameMatch = !this.searchForm.name || 
          item.name.toLowerCase().includes(this.searchForm.name.toLowerCase());
        
        // 状态筛选
        const statusMatch = this.searchForm.status === null || 
          item.status === this.searchForm.status;
        
        return nameMatch && statusMatch;
      });
    }
  },
  created() {
    this.fetchCategoriesList();
  },
  methods: {
    // 获取分类列表
    fetchCategoriesList() {
      this.loading = true;
      axios.get('/api/admin/article/category')
        .then(response => {
          if (response.data.code === 200) {
            this.categoriesList = response.data.data;
          } else {
            this.$message.error(response.data.msg || '获取分类列表失败');
          }
        })
        .catch(error => {
          console.error('获取分类列表错误', error);
          this.$message.error('获取分类列表失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 搜索
    onSearch() {
      // 前端已经通过计算属性过滤，无需额外操作
    },
    
    // 重置搜索表单
    resetSearchForm() {
      this.searchForm = {
        name: '',
        status: null
      };
    },

    // 计算状态数量
    getStatusCount(status) {
      if (!this.categoriesList) return 0;
      return this.categoriesList.filter(item => item.status === status).length;
    },
    
    // 表格行样式
    // eslint-disable-next-line no-unused-vars
    tableRowClassName({row, rowIndex}) {
      if (row.status === 1) {
        return 'enabled-row';
      } else if (row.status === 0) {
        return 'disabled-row';
      }
      return '';
    },
    
    // 打开新增对话框
    handleAdd() {
      this.dialogTitle = '新增分类';
      this.isEdit = false;
      this.categoryForm = {
        id: null,
        name: '',
        description: '',
        sortOrder: 0,
        status: 1
      };
      this.dialogVisible = true;
    },
    
    // 打开编辑对话框
    handleEdit(row) {
      this.dialogTitle = '编辑分类';
      this.isEdit = true;
      this.categoryForm = {
        id: row.id,
        name: row.name,
        description: row.description,
        sortOrder: row.sortOrder,
        status: row.status
      };
      this.dialogVisible = true;
    },
    
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const method = this.isEdit ? 'put' : 'post';
          const url = this.isEdit ? `/api/admin/article/category/${this.categoryForm.id}` : '/api/admin/article/category';
          
          axios[method](url, this.categoryForm)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success(this.isEdit ? '更新成功' : '添加成功');
                this.dialogVisible = false;
                this.fetchCategoriesList();
              } else {
                this.$message.error(response.data.msg || (this.isEdit ? '更新失败' : '添加失败'));
              }
            })
            .catch(error => {
              console.error(this.isEdit ? '更新分类错误' : '添加分类错误', error);
              this.$message.error(this.isEdit ? '更新分类失败' : '添加分类失败');
            });
        }
      });
    },
    
    // 更改状态
    handleStatus(row) {
      const newStatus = row.status === 1 ? 0 : 1;
      const statusText = newStatus === 1 ? '启用' : '禁用';
      
      this.$confirm(`确定要${statusText}该分类吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.put(`/api/admin/article/category/${row.id}`, {
          ...row,
          status: newStatus
        }).then(response => {
          if (response.data.code === 200) {
            this.$message.success(`${statusText}成功`);
            this.fetchCategoriesList();
          } else {
            this.$message.error(response.data.msg || `${statusText}失败`);
          }
        }).catch(error => {
          console.error('更新状态错误', error);
          this.$message.error(`${statusText}失败`);
        });
      }).catch(() => {
        // 取消操作
      });
    },
    
    // 删除分类
    handleDelete(row) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`/api/admin/article/category/${row.id}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('删除成功');
              this.fetchCategoriesList();
            } else {
              this.$message.error(response.data.msg || '删除失败');
            }
          })
          .catch(error => {
            console.error('删除分类错误', error);
            this.$message.error('删除失败');
          });
      }).catch(() => {
        // 取消删除操作
      });
    },
    
    // 重置表单
    resetForm(formName) {
      this.$refs[formName] && this.$refs[formName].resetFields();
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    }
  }
};
</script>

<style scoped>
.article-type-management {
  padding: 20px;
  min-height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.page-info {
  display: flex;
  align-items: center;
}

.stat-item {
  margin-left: 15px;
  font-size: 13px;
  color: #606266;
}

.box-card {
  flex: 1;
  margin-bottom: 20px;
  box-shadow: 0 4px 18px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.toolbar {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.toolbar > .el-button {
  margin-right: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.search-form .el-form-item {
  margin-bottom: 10px;
  margin-right: 10px;
}

.search-form .el-button {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 统计卡片 */
.stat-cards {
  display: flex;
  gap: 15px;
  margin: 15px 0;
}

.stat-card {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  min-width: 150px;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 40px;
  height: 40px;
  background-color: #409EFF;
  color: white;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 20px;
}

.stat-content {
  margin-left: 15px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-label {
  margin-top: 5px;
  font-size: 13px;
  color: #909399;
}

.empty-container {
  margin: 40px 0;
  text-align: center;
}

/* 表格样式 */
:deep(.enabled-row) {
  background-color: #f0f9eb;
}

:deep(.disabled-row) {
  background-color: #f5f7fa;
}

.category-name-tag {
  margin: 0;
  font-weight: bold;
}

/* 提示区域 */
.tips-container {
  margin-top: 20px;
  padding: 15px;
  display: flex;
  background-color: #f4f6fa;
  border-radius: 4px;
}

.tip-icon {
  font-size: 24px;
  color: #e6a23c;
  margin-right: 15px;
}

.tip-content {
  flex: 1;
}

.tip-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #606266;
}

.tip-text {
  color: #606266;
  font-size: 13px;
}

.tip-text p {
  margin: 5px 0;
}

/* 表单提示 */
.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1;
  padding-top: 4px;
}

/* 底部页脚 */
.page-footer {
  margin-top: auto;
  padding: 15px 0;
  text-align: center;
  color: #909399;
}

.footer-content {
  padding: 15px 0;
  border-top: 1px solid #ebeef5;
}

.footer-links {
  margin-bottom: 10px;
}

.footer-links a {
  color: #606266;
  text-decoration: none;
}

.footer-links a:hover {
  color: #409EFF;
  text-decoration: underline;
}

.divider {
  margin: 0 10px;
}

.copyright {
  font-size: 12px;
}
</style> 